package org.mapdroid.maps.gmaps.overlay.info;

import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.mapdroid.MapDroid;
import org.mapdroid.R;
import org.mapdroid.data.adt.Book;
import org.mapdroid.data.adt.Client;
import org.mapdroid.data.adt.Parking;
import org.mapdroid.login.SettingsActivity;
import org.mapdroid.login.LoginActivity;
import org.mapdroid.maps.gmaps.MdMapActivity;
import org.mapdroid.maps.gmaps.overlay.MdMarkerItemizedOverlay;
import org.mapdroid.utils.MdTimer;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ParkingInfoActivity extends Activity implements IMarkerInfo, OnClickListener{
	private TextView titleView;
	private ImageView imageView;
	private ListView parkingList;
	private Button bookButton, unbookButton;
	private Parking parking;
	private Client client;
	private String username;
	private Intent timerService;
	private int overlayId;
	private Book book;
	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
		}
	};

	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.parking_info_layout);
		
		titleView = (TextView) this.findViewById(R.id.info_name);
		imageView = (ImageView) this.findViewById(R.id.info_image);
		parkingList  = (ListView) this.findViewById(R.id.info_list);
		bookButton = (Button) this.findViewById(R.id.positive_parking_button);
		unbookButton = (Button) this.findViewById(R.id.negative_parking_button);
		parkingList.setOnItemClickListener(this);
		bookButton.setOnClickListener(this);
		unbookButton.setOnClickListener(this);
		
		timerService = new Intent(this, MdTimer.class);
		Intent parkingIntent = super.getIntent();
		parking = parkingIntent.getParcelableExtra(MdMarkerItemizedOverlay.OBJECT);
		client	= parkingIntent.getParcelableExtra(LoginActivity.CLIENT_OBJECT);
		overlayId = parkingIntent.getIntExtra(MdMarkerItemizedOverlay.OVERLAY_DATA, -1);
		
		/*for(int i=0; i<parking.getParkingList().size(); i++){
			Book tmpBook = parking.getParkingList().get(i);
			if(tmpBook.getPersonId().contentEquals(client.getUsername())){
				book = tmpBook;
			}
		}*/
		
		book = null;
		
		if(client!=null){
			username = client.getUsername();
			this.setTitle(username + " @ " + getString(R.string.parking_info_title));
		}
			
		initDialog(parking, R.layout.marker_single_voice_layout_2);
	}
	
	@Override
    public void onDestroy() {
    	super.onDestroy();
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    }

    @Override
    public void onResume(){
    	super.onResume();
    	
    	if(client == null){
			SharedPreferences pref = getApplicationContext().getSharedPreferences(MapDroid.MAPDROID_PREFERENCES, Activity.MODE_APPEND);
    		username = pref.getString(SettingsActivity.USERNAME, null);
    	}
		if(username==null){
			bookButton.setText(R.string.login_item);
		}
		else{
			this.setTitle(username + " @ " + getString(R.string.parking_info_title));
			
			int size=parking.getParkingList().size();
			List<Book> list = parking.getParkingList();
			for(int i=0; i<size; i++){
				if(list.get(i).getPersonId().contentEquals(username)){
					bookButton.setText(R.string.view_book_parking_button_text);
					unbookButton.setVisibility(Button.VISIBLE);
					book = list.get(i);
					i=size;
				}
			}
		}
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.parking_info_menu, menu);
	    return true;
	}
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	super.onOptionsItemSelected(item);
    	switch(item.getItemId()){
    		case R.id.view_service_info_item:
    			Intent infoIntent = new Intent(this, ServiceInfoActivity.class);
				infoIntent.putExtra(MdMarkerItemizedOverlay.OBJECT, parking);
				startActivityForResult(infoIntent, MdMapActivity.PARKING_INTENT_ID);
				return true;
    	}
    	
    	return false;
    }
	

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		switch(arg2){
			case 3:
				Intent infoIntent = new Intent(this, ServiceInfoActivity.class);
				infoIntent.putExtra(MdMarkerItemizedOverlay.OBJECT, parking);
				startActivityForResult(infoIntent, MdMapActivity.PARKING_INTENT_ID);
				break;
		}
	}

	@Override
	public void initDialog(Object o, int layoutResId) {
		// TODO Auto-generated method stub
		Parking parking = (Parking) o;
		
		String[] tmpStringVector = new String[3];
		tmpStringVector[0]="Label";
		tmpStringVector[1]="Value";
		tmpStringVector[2]="Image";
		
		int[] tmpId = new int[3];
		tmpId[0] = org.mapdroid.R.id.marker_voice_label;
		tmpId[1] = org.mapdroid.R.id.marker_voice_text;
		tmpId[2] = org.mapdroid.R.id.marker_icon;
		
		Map<String, Object> map = new Hashtable<String, Object>();
		List<Map<String, Object>> infoList = new LinkedList<Map<String, Object>>();
		
		//IMage
		int tmpInt = parking.getPhoto();
		if(tmpInt>0)
			imageView.setImageResource(tmpInt);
		
		//Title
		String tmpString = parking.getName();
		if(tmpString!=null)
			titleView.setText(tmpString);
		
		//Available Number
		map.put("Label", getString(R.string.available_parking_number_label));
		map.put("Value", parking.getAvailableParkingNumber());
		map.put("Image", 0);
		infoList.add(map);
		
		//Parking Number
		map = new Hashtable<String, Object>();
		map.put("Label", getString(R.string.parking_number_label));
		map.put("Value", parking.getParkingNumber());
		map.put("Image", 0);
		infoList.add(map);
		
		//Price Per Hour
		map = new Hashtable<String, Object>();
		map.put("Label", getString(R.string.parking_price_label));
		map.put("Value", parking.getPricePerHour());
		map.put("Image", 0);
		infoList.add(map);
		
		//Info
		map = new Hashtable<String, Object>();
		map.put("Label", getString(R.string.view_info_label));
		map.put("Value", getString(R.string.view_info_text));
		map.put("Image", android.R.drawable.ic_menu_more);
		infoList.add(map);
		
		SimpleAdapter adapter = new SimpleAdapter(this, infoList, layoutResId, tmpStringVector, tmpId);
		parkingList.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		final Button button = (Button) v;
		String title = (String) button.getText();
		
		if(title.contentEquals(getString(R.string.book_parking_button_text))){
			bookIn(username);
			return;
		}
		
		if(title.contentEquals(getString(R.string.login_item))){
			login();
			return;
		}
		
		if(title.contentEquals(getString(R.string.view_book_parking_button_text))){
			AlertDialog.Builder bookView = new AlertDialog.Builder(this);
			bookView.setIcon(android.R.drawable.ic_dialog_info);
			bookView.setTitle(R.string.book_info_title);
			bookView.setMessage(getString(R.string.book_info_text) + " " + book.toString());
			bookView.setNeutralButton(R.string.ok_button_text, null);
			bookView.show();
			return;
		}
		
		if(title.contentEquals(getString(R.string.unbook_parking_button_text))){
			bookOut(username);
		}
	}

	private void login() {
		// TODO Auto-generated method stub
		Intent i = new Intent(getBaseContext(), LoginActivity.class);
		startActivityForResult(i, MdMapActivity.LOGIN_INTENT_ID);
	}

	private void bookIn(final String username) {
		// TODO Auto-generated method stub
		AlertDialog.Builder bookConfirm = new AlertDialog.Builder(this);
		bookConfirm.setIcon(android.R.drawable.ic_dialog_info);
		bookConfirm.setTitle(R.string.warning_dialog_title);
		bookConfirm.setMessage(R.string.book_confirmation_dialog_text);
		bookConfirm.setPositiveButton(R.string.yes_button_text, new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				book = parking.bookingIn(username);
				if(book!=null){
					timerService.putExtra(MdMarkerItemizedOverlay.OBJECT, parking);
					timerService.putExtra(LoginActivity.CLIENT_OBJECT, username);
					timerService.putExtra(MdMarkerItemizedOverlay.OVERLAY_DATA, overlayId);
					bindService(timerService, mConnection, Service.BIND_AUTO_CREATE);
					TextView availableText = (TextView) parkingList.findViewById(R.id.marker_voice_text);
					availableText.setText(Integer.toString(Integer.parseInt((String) availableText.getText()) - 1));
					
					Toast.makeText(getBaseContext(), R.string.book_confirmed_text, Toast.LENGTH_SHORT).show();
					bookButton.setText(R.string.view_book_parking_button_text);
					unbookButton.setVisibility(Button.VISIBLE);
					
					Intent newParkingIntent = new Intent();
					newParkingIntent.putExtra(MdMarkerItemizedOverlay.OBJECT, parking);
					newParkingIntent.putExtra(MdMarkerItemizedOverlay.OVERLAY_DATA, overlayId);
					setResult(Activity.RESULT_OK, newParkingIntent);
					
					new CountDownTimer(MdTimer.TIMER_VALUE, 1000){
						@Override
						public void onFinish() {
							// TODO Auto-generated method stub
							if(parking.bookingOut(username)){
								stopService(timerService);
								Toast.makeText(getBaseContext(), R.string.unbook_parking_confirmed, Toast.LENGTH_SHORT).show();
								unbookButton.setVisibility(Button.INVISIBLE);
								bookButton.setText(R.string.book_parking_button_text);
								TextView availableText = (TextView) parkingList.findViewById(R.id.marker_voice_text);
								availableText.setText(Integer.toString(Integer.parseInt((String) availableText.getText()) + 1));
								
								/*Intent newParkingIntent = new Intent();
								newParkingIntent.putExtra(MdMarkerItemizedOverlay.OBJECT, parking);
								newParkingIntent.putExtra(MdMarkerItemizedOverlay.OVERLAY_DATA, overlayId);
								setResult(Activity.RESULT_OK, newParkingIntent);*/
								return;
							}
							return;
						}
				
						@Override
						public void onTick(long millisUntilFinished) { }
					}.start();
				}
				else
					Toast.makeText(getBaseContext(), R.string.error_dialog_title, Toast.LENGTH_SHORT).show();
			}
		});
		bookConfirm.setNegativeButton(R.string.no_button_text, null);
		bookConfirm.show();
	}
	
	private void bookOut(final String username) {
		// TODO Auto-generated method stub
		AlertDialog.Builder unbookConfirm = new AlertDialog.Builder(this);
		unbookConfirm.setIcon(android.R.drawable.ic_dialog_alert);
		unbookConfirm.setTitle(R.string.warning_dialog_title);
		unbookConfirm.setMessage(R.string.unbook_confirmation_dialog_text);
		unbookConfirm.setPositiveButton(R.string.yes_button_text, new DialogInterface.OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(parking.bookingOut(username)){
					stopService(timerService);
					Toast.makeText(getBaseContext(), R.string.unbook_parking_confirmed, Toast.LENGTH_SHORT).show();
					unbookButton.setVisibility(Button.INVISIBLE);
					bookButton.setText(R.string.book_parking_button_text);
					TextView availableText = (TextView) parkingList.findViewById(R.id.marker_voice_text);
					availableText.setText(Integer.toString(Integer.parseInt((String) availableText.getText()) + 1));
					
					Intent newParkingIntent = new Intent();
					newParkingIntent.putExtra(MdMarkerItemizedOverlay.OBJECT, parking);
					newParkingIntent.putExtra(MdMarkerItemizedOverlay.OVERLAY_DATA, overlayId);
					setResult(Activity.RESULT_OK, newParkingIntent);
					return;
				}
			}
		});
		unbookConfirm.setNegativeButton(R.string.no_button_text, null);
		unbookConfirm.show();
	}
	 
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		switch(requestCode){
			case MdMapActivity.LOGIN_INTENT_ID:
				if(resultCode == Activity.RESULT_OK){
					client = data.getParcelableExtra(LoginActivity.CLIENT_OBJECT);
					username = client.getUsername();
					MdMapActivity.client = client;
					bookButton.setText(R.string.book_parking_button_text);
					this.setTitle( username + " @ " + getString(R.string.parking_info_title));
				}
			break;
			
			case MdMapActivity.PARKING_INTENT_ID:
				if(resultCode == Activity.RESULT_OK){
					setResult(Activity.RESULT_OK, data);
					finish();
				}
			break;
		}
	}
}

